from flask import Flask, request, jsonify
from flask_cors import CORS
import base64
import requests

app = Flask(__name__)
CORS(app)


# curl --location 'https://api.sd-rtn.com/cn/api/conversational-ai-agent/v2/projects/3669d0289d81403ab8c60566607fe6b8/join/' \
# --header 'Authorization: <Basic Auth>' \
# --header 'Content-Type: application/json' \
# --data 

appId = '3669d0289d81403ab8c60566607fe6b8'
mainfile = 'ea87f0ffa0864e4d85d7efb30a6cadb8'

customer_key = 'de25362265254cd98afc0b6528a2293d'
customer_secret = '31baf1d3fa86402bbcc6fac929a4f3eb'
credential = ''
base_url = 'https://api.agora.io/cn/api/conversational-ai-agent/v2/'

group_id = '1897286461640688241'
api_key = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLkuK3lm73pgJror53mnInpmZDlhazlj7giLCJVc2VyTmFtZSI6IuS4reWbvemAmuivneaciemZkOWFrOWPuCIsIkFjY291bnQiOiIiLCJTdWJqZWN0SUQiOiIxODk3Mjg2NDYxNjQ5MDc2ODQ5IiwiUGhvbmUiOiIxMzI2MjIyMjA1MSIsIkdyb3VwSUQiOiIxODk3Mjg2NDYxNjQwNjg4MjQxIiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjUtMDMtMDcgMTY6NDc6MzgiLCJUb2tlblR5cGUiOjEsImlzcyI6Im1pbmltYXgifQ.UKWe6Lrs2d2nrqk_JEwP9P8euFjeOWkDptcuQIBidYqGNH_t7lfX3SUE4hcJFCD2Eb1s_H2t0P7NS0Mn_yPsC1Oqo7zmd10IpQ0sPjOhqDuI-mHm7w5s4HnzNqtkUop54f6wlWFYwaQjBka1qJ5_XT4u3B4VVqVfudxahp_DmjvL6baRCEENf2Fv8DBtsuyjWm8VA1_sjxRZudAe2DK9Y677GJDEgtDe8WymsPDYDgZGX7pgJdA8HNAvh7gWvfvfBSqdCX69ByirZcRCcDIZKNjKSb2qkX5-onPe3ZfppYme8-dxKbGWrhI4YqQ82JFve7K3Wj4GEdtQ0A1RP2dA-w'
deepseek_key = 'sk-b8575714afad46d2a2cd5156aa11b6b5' #阿里云deepseek https://bailian.console.aliyun.com/?apiKey=1#/api-key

channel_name = "convaiconsole_145845"
token = "007eJxTYOi4+yzzVW7c6wmLX8rYrpLot5/G2hczyzz18878F+c7rE8oMBibmVmmGBhZWKZYGJoYGCcmWSSbGZiamZkZmKelmiVZHOk+n94QyMjAdFCMlZEBAkF8ZgZDQ0MGBgCiVR9j"
# 存储消息的列表
messages = []

@app.route('/register', methods=['POST'])
def register_robot():
    data = request.json
    name = data.get('name')
    credentials = customer_key + ":" + customer_secret
    base64_credentials = base64.b64encode(credentials.encode("utf8"))
    credential = base64_credentials.decode("utf8")
    
    headers = {"Authorization": f"Basic {credential}"}
    payload = {
            "name": name,
            "properties": {
                "channel": name,
                "agent_rtc_uid": "17504",
                "remote_rtc_uids": [
                    "*"
            ],
            "enable_string_uid": True,
            "idle_timeout": 120,
                "llm": {
      "url": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
      "api_key": deepseek_key,
      "max_history": 10,
      "system_messages": [
        {
          "role": "system",
          "content": ""
        }
      ],
      "params": {
        "model": "qwen-turbo",
        "max_token": 1024
      },
      "greeting_message": "你好呀，有什么可以帮您？",
      "failure_message": "我出错了，请稍等！"
    },
        "asr": {
        "language": "zh-CN"
        },
        "vad": {
        "interrupt_duration_ms": 160,
        "prefix_padding_ms": 300,
        "silence_duration_ms": 480,
        "threshold": 0.5
        },
        "tts": {
        "vendor": "minimax",
        "params": {
            "group_id": group_id,
            "key": api_key,
            "model": "speech-01-turbo-240228",
            "voice_settings": {
                "voice_id": "female-shaonv",
                "speed": 1,
                "vol": 1,
                "pitch": 0,
                "emotion": "neutral"
            }
        }
        },
        "parameters": {
            "transcript": {
                "enable": True,
                "protocol_version": "v2",
                "enable_words": False,
                "redundant": False
            },
            "enable_metrics": True,
            "audio_scenario": "default"
        },
        "token": token,
        "advanced_features": {
            "enable_aivad": False
        }
        }
    }
    response = requests.request("post", 
                                f"https://api.sd-rtn.com/cn/api/conversational-ai-agent/v2/projects/3669d0289d81403ab8c60566607fe6b8/join/",
                                json=payload, headers=headers)
    print(response.text)
    if response.status_code == 200:
        return jsonify({'status': 'success', 'content': response.text}), 200
    else:
        return jsonify({'status': 'error', 'content': ''}), 500
    
@app.route('/leave', methods=['POST'])   
def leave_robot():
    agentId = request.json.get('agentId')
    credentials = customer_key + ":" + customer_secret
    base64_credentials = base64.b64encode(credentials.encode("utf8"))
    credential = base64_credentials.decode("utf8")

    headers = {"Authorization": f"Basic {credential}"}
    url = "https://api.agora.io/cn/api/conversational-ai-agent/v2/projects/3669d0289d81403ab8c60566607fe6b8/agents/"+agentId+"/leave"
    print(url)
    response = requests.post(url=url, headers=headers)
    print(response.text)
    if response.status_code == 200:
        return jsonify({'status': 'success', 'content': response.text}),200
    else:
        return jsonify({'status': 'error', 'content': response.text}),500
    


    
@app.route('/send_message_to_agora', methods=['POST'])
def send_message_to_agora():
    agentId = request.json.get('agentId')
    message = request.json.get('message')
    if agentId and message:
        headers = {
            "Authorization": f"Basic {credential}",
            'Content-Type': 'application/json'
        }
        url = f"https://api.agora.io/cn/api/conversational-ai-agent/v2/projects/3669d0289d81403ab8c60566607fe6b8/send-message"
        print(url)
        response = requests.post(url, json={
            "name":channel_name,
            "message": f"{message}"
            },headers=headers)
        print(response.status_code)
        if response.status_code == 200:
            return jsonify({'status': 'success', 'content': response.text}), 200
        else:
            return jsonify({'status': 'error', 'content': response.text}), 500


@app.route('/send_message', methods=['POST'])
def send_message():
    data = request.json
    message = data.get('message')
    if message:
        messages.append(message)
        return jsonify({'status': 'success', 'message': 'Message received'}), 200
    else:
        return jsonify({'status': 'error', 'message': 'No message provided'}), 400

@app.route('/get_messages', methods=['GET'])
def get_messages():
    return jsonify({'messages': messages}), 200

if __name__ == '__main__':
    app.run(debug=True)